#include "stdafx.h"
#include "Recv.h"

int CRecv::receive()
{
	int iResult = 0;
	char szBuffer[MaxBufferSize];
	int iTotalLength = m_Data.length();

	while (true)
	{
		memset(szBuffer, 0, MaxBufferSize);
		iResult = recv(m_ServerSocket, szBuffer, MaxBufferSize, 0);

		iTotalLength += iResult;

		if (iResult > 0) {
			m_Data.append(szBuffer, iResult);

			if (Done(iTotalLength))break;

		}
		else
			break;
	}

	return iTotalLength;
}

void CRecv::Exchange()
{
	int iResult = 0;
	char szBuffer[MaxBufferSize];
	int iTotalLength = m_Data.length();

	if (send(m_ClientSocket, m_Data.c_str(), m_Data.length(), 0) <= 0)return;

	while (true)
	{
		if (iTotalLength == m_Length)break;
		memset(szBuffer, 0, MaxBufferSize);
		iResult = recv(m_ServerSocket, szBuffer, MaxBufferSize, 0);

		iTotalLength += iResult;

		if (iResult > 0) {
			if (send(m_ClientSocket, szBuffer, iResult, 0) <= 0)break;

			if (Done(iTotalLength))break;

		}
		else
			break;
	}

	return;
}

string & CRecv::getData()
{
	return m_Data;
}

void CRecv::append(const string & str)
{
	m_Data.append(str);
}

void CRecv::clear()
{
	m_Data.clear();
}

int CRecv::getReceiveLength()const
{
	return m_Data.length();
}

bool CRecv::Done(int iLen)
{
	if (m_Length != -1) {
		if (iLen == m_Length)
		{
			return true;
		}
	}
	return false;
}
